package com.hantang.web.json.handlers;

import java.util.Date;

import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

import com.google.gson.Gson;
import com.hantang.web.dao.NewMessageDao;
import com.hantang.web.data.NewMessageData;
import com.hantang.web.json.ds.MetaData;
import com.hantang.web.json.res.StringRes;

public class AddNewsHandler extends AbstractHandler {

	private static Logger logger = Logger.getLogger(AddNewsHandler.class);
	
	@Override
	public String doService(Request req, Response resp) throws Exception {
		String title = req.getParameter("title");
		String highlight = req.getParameter("highlight");
		String content = req.getParameter("content");
		
		String sret = handleServlet(title, highlight, content);
		
		return sret;
	}

	public static String handleServlet(String title, String highlight, String content) {
		logger.info("title: " + title + " highlight:" + highlight);
		
		NewMessageData data = new NewMessageData();
		data.setContent(content);
		data.setTitle(title);
		if(highlight != null){
			data.setHighlight(Short.valueOf(highlight.trim()));			
		}
		data.setCreateDate(new Date());
		
		long id = handle(data);
		StringRes sres = new StringRes();
		
		sres.setData(""+ id);
		sres.setMeta(new MetaData(MetaData.META_DATA_SUCCESS_CODE, "Succ"));
		
		Gson gson = new Gson();
		String sret= gson.toJson(sres);
		return sret;
	}
	
	public static long handle(NewMessageData data)
	{
		NewMessageDao dao = new NewMessageDao();
		long id = dao.saveData(data);
		return id;
	}
	
}
